<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\controllers\wx\services\Wx;
use app\models\product\Product;
use app\models\product\Product as Model;
use app\models\product\ProductAreaList;
use app\models\product\ProductSku;
use app\models\system\SetExpressCity;
use app\models\system\SetFlow;
use app\models\system\SetWx;
use app\models\user\User;
use app\models\ZRegion;
use app\redis\Cache;
use app\util\Qrcode;
use app\util\Request;
use app\util\Util;
use app\controllers\h5\services\Product as Service;
use yii\imagine\Image;

/**
 * Class ProductController
 * @package app\controllers\h5
 */
class ProductController extends H5Controller
{
    /**
     * like product
     *
     * @return \yii\web\Response
     */
    public function actionLike()
    {
        $key = Cache::$PRODUCT_LIKE;
        $cache = Cache::get($key);
        if (!$cache || true) {
            $num = SetFlow::getLastOne();
            $num = $num->recommend_num;

            $list = Model::find()
                ->where(['status' => Model::$statusMapping['OK']])
                ->andWhere(['is_recommend' => 1])
                ->orderBy(['is_recommend' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC])
                ->limit($num)
                ->with(['mainImage'])
                ->asArray()
                ->all();

            // Cache::set($key, json_encode($list));
        } else {
            $list = json_decode($cache, true);
        }

        return $this->successEncode($list);
    }

    /**
     * all product list
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $key = Cache::$PRODUCT_LIST . $page;
        $cache = Cache::get($key);
        if (!$cache) {
            $query = Model::find()
                ->where(['status' => Model::$statusMapping['OK']]);

            $totalCount = $query->count();
            $totalPage = ceil($totalCount / $pageSize);

            $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->with(['mainImage', 'scoreCost'])
                ->asArray()
                ->all();

            Cache::set($key, json_encode([
                'totalCount' => $totalCount,
                'totalPage' => $totalPage,
                'list' => $list
            ]));
        } else {
            $data = json_decode($cache, true);
            $totalCount = $data['totalCount'];
            $totalPage = $data['totalPage'];
            $list = $data['list'];
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    /**
     * product detail
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionDetail()
    {
        $id = $this->post('id');

        $key = Cache::$PRODUCT_DETAIL . $id;
        $cache = Cache::get($key);
        if (!$cache || true) {
            $data = Model::find()
                ->where(['status' => Model::$statusMapping['OK']])
                ->andWhere(['id' => $id])
                ->with([
                    'mainImage',
                    'image', 'image.image',
                    'brand', 'brand.image',
                    'area', 'area.name',
                    'properties',
                    'scoreCost',
                    'sku', 'skuName', 'skuName.values', 'sku.image',
                    'scoreCost'
                ])
                ->asArray()
                ->one();
            if ($data) {

                // freight area
                // $list = SetExpressCity::getName();
                // $data['expressCity'] = $list;

                // area (select first & check group area)
                $area = $data['area'];
                if (is_array($area) && count($area) > 0) {
                    $data['isGroup'] = Service::checkGroupArea($area);
                    $data['area'] = $area[0];
                } else {
                    $data['area'] = null;
                    $data['group'] = false;
                }

                // content images list
                $convert = Util::convertImages($data['content']);
                $data['inImages'] = $convert['images'];
                $data['inText'] = $convert['text'];
                unset($data['content']);

                // sku
                if (is_array($data['sku'])) {
                    foreach ($data['sku'] as &$item) {
                        $item['sku_values'] = ProductSku::skuValue($item['sku_list']);
                    }
                }

                Cache::set($key, json_encode($data));
            }
        } else {
            $data = json_decode($cache, true);
        }

        if ($data) {

            // 偏远地区
            $set = SetExpressCity::getLastOne()['province'];
            if ($set) {
                $names = ZRegion::find()
                    ->where(['code' => $set])
                    ->select(['name'])
                    ->column();
                // $data['logistics'] = join(', ', $names);
                $data['logistics'] = $names;
            } else {
                // $data['logistics'] = '';
                $data['logistics'] = [];
            }

            // 新运费说明
            // $data['freightText'] = '4元/每单, 10元/箱';

            // 真实商品运费
            // $data['freightText'] = $data['freight'] . '元';

            // var_dump($data['logistics']);exit;

            // 第3次修改运费
            $cities = join(', ', $data['logistics']);
            $f = floatval($data['freight']);
            $rf = floatval($data['remote_freight']);
            $data['freightText'] = "{$f}元";
            if ($cities) {
                $data['freightText'] .= ", 偏远地址运费: {$rf}元(包括: $cities)";
            }

            return $this->successEncode($data);
        }

        return $this->fail('商品不存在');
    }

    // 显示复购价格
    public function actionDisplayRepeatPrice()
    {
        $id = $this->post('id');
        $product = Model::findOne(['id' => $id]);

        if ($this->user && $product && ProductAreaList::checkInArea($id, Model::$areaMap['REPEAT'])) {
            // var_dump($data['price']);exit;
            $price = Model::getPriceByLevel($id, $this->user->id, $product['price']);

            return $this->successEncode(['price' => $price]);
        }

        return $this->successEncode(['price' => $product['price']]);
    }

    // qrcode share
    public function actionQrcodeShare()
    {
        $id = $this->post('id');
        $url = $this->post('url');
        $color = $this->post('color');

        $name = '/qrcode/product-share/' . $id . '.png';
        $path = \Yii::$app->getBasePath() . '/web' . $name;

        // if (!file_exists($path)) {
        //     Qrcode::generate($url, $name, 100, $color);
        // }

        Qrcode::generate($url, $name, 100, $color);

        return $this->successEncode([
            'image' => $name
        ]);
    }

    // mini product qrcode
    public function actionQrcodeShareMini()
    {
        // product id
        $product_id = $this->post('id');

        $set = SetWx::getLastOne(false);

        // product_id-user_id
        $scene = $product_id . '-' . $this->user->id;
        // 页面 page，例如 pages/index/index，根路径前不要填加 /
        // $page = 'sub_product/pages/detail/index?id=' . $product_id;

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web/qrcode/product-mini/' . $scene . '.png';

        if (!file_exists($path)) {
            $access_token = Wx::getAccessToken();

            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            // $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 280, 'page' => $page]));
            $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 280]));

            // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html#%E8%B0%83%E7%94%A8%E6%96%B9%E5%BC%8F
            // 这里要判断成功否


            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }

            // wx qrcode
            file_put_contents($path, $result);

            // 注意, 经常遇到  Unable to open image 文件打不开,
            // 是因为这里输出的图片不成功, 有问题

        }

        // product
        $product = Product::find()
            ->where(['id' => $product_id])
            ->with(['mainImage'])
            ->asArray()
            ->one();
        if ($product) {
            $qrcode = '/qrcode/product-mini/' . $scene . '.png';
            $bg = '/product-qrcode-bg.png';
            $save = '/qrcode/product-mini/' . $scene . '-product.png';


            Qrcode::setPoster($qrcode, $bg, $save, [450, 900]);

            $image = $product['mainImage']['thumbnail_path'];
            if (!file_exists(\Yii::$app->getBasePath() . '/web' . $image)) {
                return $this->fail('产品主图不存在');
            }
            Qrcode::setPoster($image, $save, $save, [0, 100]);
            Qrcode::setText($save, $product['title'], '', [10, 50], 24, '#333333');
            Qrcode::setText($save, '￥' . $product['price'], '', [10, 900], 36, '#ff0000');
            $user = User::findOne(['id' => $this->user->id]);
            if ($user && $user->nickname) {
                Qrcode::setText($save, base64_decode($user->nickname) . '为您推荐', '', [10, 1000], 24, '#666666');
            }// 缩小, 不然文件太大
            $result = $base . '/web' . $save;
            Image::thumbnail($result, 375, 667)->save($result);


            return $this->success([
                'path' => $save
            ]);

        }

    }
}